import axios from 'axios';
import qs from 'qs';
import { getHeaders } from '@/utils/utils';
import { useMessage } from 'naive-ui';
import { useRouter } from 'vue-router';
const router = useRouter();
const message = useMessage();

const ENV = import.meta.env as any;

const getRequestBody = (config: any) => {
  const { method, data, params } = config;
  let body = '';
  if (method === 'get' || method === 'delete') {
    // get和delete 取消encode 编码 防止出现和后台签名错误问题
    body = qs.stringify(params, { encode: false });
  } else {
    body = data ? JSON.stringify(data) : '';
  }
  return body;
};

const service: any = axios.create({
  // ehl_oss_transfer
  baseURL: ENV.VITE_BASE_URL,
  timeout: 50000, // 请求超时时间
});
// request拦截器
service.interceptors.request.use((config: any) => {
  const configInfo = config;
  const body = getRequestBody(config);
  configInfo.headers = getHeaders(body);
  console.log(
    `%c ${config.name}  ${config.url}-参数:`,
    'color:#FF0099;',
    config.params || config.data
    // configInfo.headers,
  );
  return configInfo;
});

// response拦截器
service.interceptors.response.use(
  async (response: any) => {
    // 关闭加载中提示
    const res = response.data;
    console.log(`%c ${response.config.name} 结果 `, 'color:#FF0099;', res);
    const { code, msg = '系统错误' } = res;
    if (code === '0000' || code === 200 || code === 1) {
      return Promise.resolve(res);
    }
    if (
      code === 'gateway_9996' ||
      code === 'amp-oss-gateway_9996' ||
      code === 'amp-oss-gateway_9997' ||
      code === 9996 ||
      code === 6996
    ) {
      router.push('/login');
    } else if (code === 9999 || code === 999999) {
      message.error('系统开小差了，请稍后再试');
    } else {
      console.log(message, '123');
      message.error(msg);
    }
    return Promise.reject(res);
  },
  (error: any) => {
    try {
      const errInfo = JSON.parse(JSON.stringify(error)) ?? {};
      message.error(errInfo?.message ?? '服务器开小差了，请稍后再试');
      console.log(errInfo, '服务器问题');
    } catch (errorMsg) {
      console.log(errorMsg);
    }
    return Promise.reject(error);
  }
);

const withoutDataMethod = (method?: any, url?: any, params?: any, config = {}) =>
  service[method](url, {
    params,
    ...config,
  });

const withDataMethod = (method?: any, url?: any, data?: any, config = {}) =>
  service[method](url, data, config);

const fetchMethod = <T>(info: any): T => {
  const { method, url, name, params, config } = info;
  if (method === 'get' || method === 'delete') {
    return withoutDataMethod(method, url, params, {
      name,
      ...config,
    });
  }
  return withDataMethod(method, url, params, {
    name,
    ...config,
  });
};

export const GET = (...rest: any[]) => withoutDataMethod('get', ...rest);
export const DELETE = (...rest: any[]) => withoutDataMethod('delete', ...rest);
export const PUT = (...rest: any[]) => withDataMethod('put', ...rest);
export const POST = (...rest: any[]) => withDataMethod('post', ...rest);

export default fetchMethod;
